package com.woorigil.social.controller.main;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.woorigil.social.Context;
import com.woorigil.social.DateUtils;
import com.woorigil.social.controller.AddCommonParamsAware;
import com.woorigil.social.controller.BaseController;
import com.woorigil.social.controller.CookieUtils;
import com.woorigil.social.domain.deal.DealCondition;
import com.woorigil.social.domain.deal.DealDao;
import com.woorigil.social.domain.deal.DealService;
import com.woorigil.social.domain.deal.DealViewList;
import com.woorigil.social.domain.deal.MainDealService;
import com.woorigil.social.domain.searcher.QueryAnalyzer;

@Controller
public class MainController extends BaseController implements AddCommonParamsAware {
	@Autowired DealDao dealDao;
	@Autowired DealService dealService;
	@Autowired MainDealService mainDealService;
	@Autowired QueryAnalyzer queryAnalyser;

	@RequestMapping("/main")
	public ModelAndView main(DealCondition condition, HttpServletRequest request) throws UnsupportedEncodingException {
		if (condition.getType() == DealCondition.Type.FREE_DEAL) {
			condition.setFree(true);
		}
		condition.setCategoryIds(getSubCategoryIds());
		
		ModelAndView mav = new ModelAndView(getForwordPage("social/search"));
		mav.addObject("totalDealCount", Context.getTotalDealCount());
		mav.addObject("lastUpdatedAt", Context.getLastUpdatedAt());
		mav.addObject("popularQueries", queryAnalyser.findQueries(20));
		mav.addObject("recentDealViewList", getRecentViewDeals(CookieUtils.getValue(request, "RECENT_VIEW_DEALS")));
		mav.addObject("recentQueries", getRecentQueries(CookieUtils.getValue(request, "RECENT_QUERIES")));
		mav.addObject("condition", condition);
//		if (condition.getCategoryIds() == null) {
//			mav.addObject("mainDealViewList", mainDealService.findMainDeals(10));
//		}
		mav.addObject("searchDealViewList", dealService.search(condition));
		return mav;
	}

	private DealViewList getRecentViewDeals(String recentView) {
//		if (StringUtils.isBlank(recentView)) {
			return new DealViewList("", null);
//		}
//		String[] dealIds = StringUtils.split(recentView, ",");
//		DealCondition condition = new DealCondition();
//		for (String each : dealIds) {
//			condition.addDealIds(NumberUtils.toInt(StringUtils.trim(each), 0));
//		}
//		return dealService.search(condition);
	}
	
	private List<String> getRecentQueries(String values) {
		List<String> results = new ArrayList<String>();
		if (StringUtils.isBlank(values)) {
			return new ArrayList<String>();
		}
		try {
			String[] tempArray = StringUtils.split(URLDecoder.decode(values, "UTF-8"), ",");
			if (tempArray != null) {
				for (String each : tempArray) {
					if (!results.contains(each)) {
						results.add(each);
					}
				}
			}
		} catch (Exception e) {
		}
		return results;
	}

	@RequestMapping("/search")
	public ModelAndView search(DealCondition condition, HttpServletRequest request, HttpServletResponse response) {
		if (condition.getType() == DealCondition.Type.FREE_DEAL) {
			condition.setFree(true);
		}
		
		condition.setCategoryIds(getSubCategoryIds());
		queryAnalyser.inputQuery(condition.getQuery());
		List<String> recentQueries = getRecentQueries(CookieUtils.getValue(request, "RECENT_QUERIES"));
		
		if (StringUtils.isNotBlank(condition.getQuery())) {
			if (!recentQueries.contains(condition.getQuery())) {
				recentQueries.add(0, condition.getQuery());
			}
			addRecentQuery(condition.getQuery(), request, response);
		}
		
		ModelAndView mav = new ModelAndView(getForwordPage("social/search"));
		mav.addObject("searchDealViewList", dealService.search(condition));
		mav.addObject("recentDealViewList", getRecentViewDeals(CookieUtils.getValue(request, "RECENT_VIEW_DEALS")));
		mav.addObject("recentQueries", recentQueries);
		mav.addObject("totalDealCount", Context.getTotalDealCount());
		mav.addObject("lastUpdatedAt", Context.getLastUpdatedAt());
		mav.addObject("popularQueries", queryAnalyser.findQueries(20));
		mav.addObject("condition", condition);
		return mav;
	}

	private void addRecentQuery(String query, HttpServletRequest request, HttpServletResponse response) {
		try {
			String cookieValue = CookieUtils.getValue(request, "RECENT_QUERIES");
			String recentQueries = null;
			if (StringUtils.isNotBlank(cookieValue)) {
				recentQueries = URLDecoder.decode(cookieValue, "UTF-8");
			}
			if (StringUtils.isBlank(recentQueries)) {
				recentQueries = query;
			} else {
				recentQueries = query + "," + recentQueries;
			}
			CookieUtils.addCookie(response, "RECENT_QUERIES", URLEncoder.encode(recentQueries, "UTF-8"), DateUtils.ONE_YEAR);
		} catch (Exception e) {
		}
	}
	
	@RequestMapping("/recentViews")
	public ModelAndView recentViews(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView(getForwordPage("social/includeRecentView"));
		mav.addObject("recentDealViewList", getRecentViewDeals(CookieUtils.getValue(request, "RECENT_VIEW_DEALS")));
		return mav;
	}
}
